package mianyang.zhangsan.com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import mianyang.zhangsan.com.pojo.*;
import mianyang.zhangsan.com.service.BookOrderService;
import mianyang.zhangsan.com.service.RoomService;
import mianyang.zhangsan.com.service.RoomTypeService;
import mianyang.zhangsan.com.service.UserService;
import mianyang.zhangsan.com.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private BookOrderService bookOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoomTypeService roomTypeService;
    @Autowired
    private RoomService roomService;

    /**
     * 前端查询订单数据
     * @param pageNo
     * @param model
     * @return
     */
    @RequestMapping("/frontList")
    public String frontList(@RequestParam("pageNo")int pageNo, Model model){
        Page<BookOrder> bookOrderPage = bookOrderService.queryPages(pageNo);
        model.addAttribute("orders", bookOrderPage.getRecords());
        List<User> users = new ArrayList<>();
        List<Room> rooms = new ArrayList<>();
        List<RoomType> roomTypes = new ArrayList<>();
        for (BookOrder bookOrder:bookOrderPage.getRecords()){
            User user = userService.queryUserInfo(bookOrder.getUser());
            Room room = roomService.queryRoomInfo(bookOrder.getRoom());
            RoomType roomType = roomTypeService.queryRoomTypeInfo(bookOrder.getRoomType());
            users.add(user);
            rooms.add(room);
            roomTypes.add(roomType);
        }
        bookOrderPage.setRecords(null);
        model.addAttribute("page", bookOrderPage);
        model.addAttribute("pages", bookOrderPage.getPages());
        model.addAttribute("rooms", rooms);
        model.addAttribute("users", users);
        model.addAttribute("roomTypes", roomTypes);
        return "order/bookOrder_front_result";
    }

    /**
     * 后台跳转订单添加页面
     * @return
     */
    @RequestMapping("/toAdd")
    public String orderToAdd(){
        return "order/bookOrder_add";
    }

    /**
     * 后台添加订单请求
     * @param order
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public String orderAdd(BookOrder order){
        System.out.println(order);
        bookOrderService.addOrder(order);
        return "{\"success\": true}";
    }

    /**
     * 后台跳转订单管理页面
     * @return
     */
    @RequestMapping("/query")
    public String query(){
        return "order/bookOrder_query_result";
    }

    /**
     * 后台查询订单数据
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/list", produces="application/json;charset=utf-8")
    @ResponseBody
    public String list(int page, int rows, BookOrder order){
        System.out.println(order);
        Page<BookOrder> orderPage = bookOrderService.queryPagesWrapper(page, rows, order);
        JSONObject response = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        response.put("total", orderPage.getPages());
        for(BookOrder item:orderPage.getRecords()){
            OrderCustom orderCustom = bookOrderService.packing(item);
            orderCustom.setRoomType(roomTypeService.queryRoomTypeInfo(item.getRoomType()).getRoomTypeName());
            Object o = JSON.toJSON(orderCustom);
            jsonArray.add(o);
        }
        response.put("rows", jsonArray);
        return response.toString();
    }

    /**
     * 后台更新订单信息
     * @param order
     * @param orderId
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String updateOrder(BookOrder order, int orderId){
        bookOrderService.updateOrder(orderId, order);
        return "{\"success\": true}";
    }

    /**
     * 后台删除订单信息
     * @param orderIds
     * @return
     */
    @RequestMapping("/deletes")
    @ResponseBody
    public String deletes(String orderIds){
        bookOrderService.deletes(orderIds);
        return "{\"success\":true}";
    }

    /**
     * 后台导出新闻信息
     * @param order
     * @param response
     */
    @RequestMapping("/outToExcel")
    public void toExcel(BookOrder order, HttpServletResponse response){
        List<BookOrder> orders = bookOrderService.queryListByWrapper(order);
        String[] headers = {"序号", "房间号", "房间类型", "预定人", "入住时间" , "入住天数", "金额", "备注", "订单状态", "交易时间"};
        String title = "订单表";
        List<String[]> contents = new ArrayList<>();
        for (BookOrder item : orders){
            contents.add(new String[]{item.getOrderId().toString(),item.getRoom(),item.getRoomType().toString(),item.getUser(),
                    item.getLiveDate(), item.getDays().toString(), item.getMoney().toString(), item.getOrderMemo(),item.getOrderState(),item.getOrderTime()});
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setHeader("Content-disposition","attachment; filename="+"order.xls");//filename是下载的xls的名，建议最好用英文
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma","No-cache");//设置头
            response.setHeader("Cache-Control","no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头
            ExcelUtils.exportExcel(title, headers, contents, out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
